const gulp = require('gulp'),
    // connect = require('gulp-connect'),
    pug = require('gulp-pug'),
    sass = require('gulp-sass'),
    // jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    concat = require('gulp-concat'),
    changed = require('gulp-changed'),
    changedInPlace = require('gulp-changed-in-place'),
    newer = require('gulp-newer'),
    wait = require('gulp-wait2'),
    debug = require('gulp-debug'),
    rename = require('gulp-rename'),
    // pkg = require('./resources/assets/config.build.json'),
    gutil = require('gulp-util'),
    // copy = require('gulp-copy'),
    cssimport = require("gulp-cssimport"),
    lineEnding = require('gulp-line-ending-corrector');

var extractMedia = require('gulp-extract-media-queries'),
    cleanCSS = require('gulp-clean-css'),
    addsrc = require('gulp-add-src');

// const gulp_conf = pkg.gulpConf;

const assets_dir = './src';
const _assets_dir = '!./src';

var browserSync = require('browser-sync').create();
var sass_changed_type = 'all',
    pug_changed_type = 'single',
    js_changed_type = '',
    js_change_cache = {};

function getHtmlFiles(){
  var srcs = {
      single: gulp.src([assets_dir + '/pug/**/*.pug', _assets_dir + '/pug/_part/*']).pipe(changed('./', {extension: '.php'})), // Only changed pages
      all: gulp.src([assets_dir + '/pug/**/*.pug', _assets_dir + '/pug/_part/*']), // All Pages
    };

  return srcs[pug_changed_type]
    .pipe(debug({title: '编译'}))
    .pipe(pug({pretty: true, basedir: assets_dir +'/pug'}));
}

gulp.task('webserver', function() {
  // connect.server({
  //   port: 8080,
  //   livereload: true
  // });
  browserSync.init({
    port: 8088,
    ui: {
      port: 8089
    },
    proxy: {
      target: 'dev.riant.me',
      middleware: function (req, res, next) {
        next();
      }
    }
  });
});

gulp.task('watch', function(){
  var sass_watch = gulp.watch([assets_dir + '/sass/**/*.scss'], ['css']);
  var js_watch = gulp.watch([assets_dir + '/js/**/*.js'], ['js-reload']);
  var vendor_js_watch = gulp.watch([assets_dir + '/vendors/**/*.js'], ['js-reload']);
  // var pug_watch = gulp.watch(['resources/views/**/*.pug'], ['clear-cache-then-reload']);
    // .on('change', browserSync.reload);
  var html_watch = gulp.watch([assets_dir + '/pug/**/*.pug'], ['html-reload']);

  sass_watch.on('change', function(event){
    var paths = event.path.split('\\');
    sass_changed_type = paths[paths.length-1].indexOf('_') === 0 ? 'all' : 'changed';
  });

  js_watch.on('change', function(event){
    if(event.path.indexOf('\\units\\') > 0){ // /libs/*
      js_changed_type = 'units';
    // } else if( event.path.indexOf('\\vendors\\') > 0 ){ // /vendors/
    //   js_changed_type = 'vendors';
    } else {
      js_changed_type = 'normal';
    }
  });

  vendor_js_watch.on('change', function(event){
    js_changed_type = 'vendors';
  });
  // pug_watch.on('change', function(event){
  //   var paths = event.path.split('\\');
  //   pug_changed_type = (paths[paths.length-2] === 'part' || paths[paths.length-1].indexOf('_') === 0) ? 'part' : 'single';
  // });
  html_watch.on('change', function(event){
    var paths = event.path.split('\\');
    pug_changed_type = (paths[paths.length-2] === '_part' || paths[paths.length-1].indexOf('_') === 0) ? 'all' : (paths[paths.length-2] === 'uc' ? 'ucenter' : 'single');
  })
});

// gulp.task('js-reload', ['jsdeploy'], function(done){
//   browserSync.reload();
//   done();
// });

gulp.task('html-reload', ['html'], function(done){
  browserSync.reload();
  done();
})

gulp.task('css', function(){
  var srcs = [assets_dir + '/sass/**/*.scss'];

  if( sass_changed_type === 'changed' ) srcs.push('!' + assets_dir + '/sass/**/_*.scss');
  // console.log('srcs == ' + srcs[2]);
  var $srcs = gulp.src(srcs).pipe(sourcemaps.init());

  $srcs = sass_changed_type === 'all' ? $srcs : $srcs.pipe(changed('./css', {extension: '.css'}));
  return $srcs.pipe(debug({title: '编译：'}))
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(cssimport())
    .pipe(lineEnding({eolc: 'LF', encoding:'utf8'}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./css'))
    .pipe(browserSync.stream({match: '**/*.css'}));
});

gulp.task('html', function(){
  return getHtmlFiles()
    .pipe(rename(function(path){ path.extname = ".php";}))
    .pipe(gulp.dest('./'));
    // .pipe(connect.reload);
});

// gulp.task('jshint', function(){
//   return gulp.src(assets_dir + '/js/**/*.js')
//     .pipe(changedInPlace({firstPass: true}))
//     .pipe(debug({title: '校验：'}))
//     .pipe(jshint())
//     .pipe(jshint.reporter('default'));
// });

// gulp.task('jsdeploy', ['jshint'], function(){
//   if( js_changed_type ){
//     var options = gulp_conf.js[js_changed_type];
//     return jsThings(options, js_changed_type === 'normal' ? gulp.src(options.src).pipe(changedInPlace({firstPass: true, cache: js_change_cache})) : undefined);

//     if( js_changed_type === 'vendors' ){
//       jsThings(gulp_conf.js['vendors']);
//     }
//   } else {

//     for(var key in gulp_conf.js){
//       jsThings(gulp_conf.js[key]);
//     }
//   }
// });

function jsThings(options, $srcs){
  var dest_dir = './js' + (options.dest_dir ? options.dest_dir : '');
  var rename_arg = typeof options.uglify === 'string' ? options.uglify : function(path){ path.extname = ".min.js";}
  var the_src = $srcs ? $srcs : gulp.src(options.src);

  if( options.copy ){
    the_src = the_src.pipe(debug({title: '复制：'})).pipe(gulp.dest(dest_dir));
  }

  the_src.pipe(sourcemaps.init());

  if( options.concat ){ // 需要合并
    the_src = the_src
      .pipe(concat(options.concat))
      .pipe(debug({title: '合并完成：'}))
      .pipe(gulp.dest(dest_dir));
  }

  if( options.uglify ){
    the_src = the_src.pipe(debug({title: '压缩：'})).pipe(uglify()) // 压缩
      .pipe(rename(rename_arg)) // 压缩文件重命名
      .pipe(sourcemaps.write('./'))
      .pipe(lineEnding({eolc: 'LF', encoding:'utf8'}))
      .pipe(gulp.dest(dest_dir));
  }
}

gulp.task('cssdeploy', ['css.concat'], function(){
  cssExtractMedias(gulp.src('./css/all.css'), 'all-pc.css')
  cssExtractMedias(gulp.src('./css/global.css'), 'global-pc.css')
});

function cssExtractMedias($src, saveAs) {
  // 抽离，合并，压缩
  $src.pipe(extractMedia((fileName, name) => {
        return name.indexOf('min-width-768') !== -1 || name.indexOf('min-width-1024') !== -1 || name.indexOf('min-width-1300') !== -1
      }))
      .pipe(concat(saveAs))
      .pipe(cleanCSS({level: 2, compatibility: 'ie8'}))
      .pipe(gulp.dest('./css/medias'));
}

// 合并 app, global ，并压缩
gulp.task('css.concat', function () {
  console.log('合并 app, global 为 all')
  var stream = gulp.src(['./css/global.css', './css/app.css'])
    .pipe(concat('all.css'))
    .pipe(cleanCSS({compatibility: 'ie7'}))
    .pipe(gulp.dest('./css'));
  return stream
});

gulp.task('default', ['webserver', 'watch']);
